package com.quotes.io;

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
import org.apache.log4j.Logger;
import com.quotes.datamodell.Quotes;
import com.quotes.datamodell.QuotesList;
import com.quotes.datamodell.Symbol;
import com.quotes.datamodell.SymbolList;
import com.quotes.dates.TimeRange;

public class YahooQuotesReader {
	private Logger logger = Logger.getLogger(getClass().toString());
	private SymbolList symbols;
	
	public YahooQuotesReader(SymbolList symbols) {
		this.symbols = symbols;
		
		logger.debug("YahooQuotesReader created!");
	}
	
	public QuotesList loadQuotes(TimeRange range) throws Exception {
		QuotesList list = new QuotesList();
		
		for (Symbol symbol : this.symbols.getSymbols()) {
			Quotes quotes = loadQuotes(symbol, range);
			list.add(quotes);
		}
		
		return list;
	}

	public Quotes loadQuotes(Symbol symbol, TimeRange range) throws Exception {
		logger.debug("Loading quotes for symbol " + symbol.getYahooName() + " from " + 
				range.getStart().toString() + " to " + range.getEnd().toString() +  " from Yahoo!");

		Quotes quotes = new Quotes(symbol);
		URL url = constructUrl(quotes.getSymbol().getYahooName(), range);
		String[] result = readFromUrl(url);
		SimpleDateFormat sdfToDate = new SimpleDateFormat("yyyy-MM-dd" );
		
		for (String item : result) {
			String[] parts = item.split(",");

			Date date = sdfToDate.parse(parts[0]);
			double open = Double.valueOf(parts[1]);
			double high = Double.valueOf(parts[2]);
			double low = Double.valueOf(parts[3]);
			double close = Double.valueOf(parts[4]);
			double volume = Double.valueOf(parts[5]);
			double adjclose = Double.valueOf(parts[6]);

			quotes.addQuote(date, open, close, high, low, volume, adjclose);
		}
		
		return quotes;
	}
	
	private URL constructUrl(String symbol, TimeRange range) throws Exception {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(range.getStart());
		
		StringBuilder uri = new StringBuilder();
		uri.append("http://ichart.finance.yahoo.com/table.csv");
		uri.append("?s=").append(symbol);
		uri.append("&a=").append(calendar.get(Calendar.MONTH));
		uri.append("&b=").append(calendar.get(Calendar.DAY_OF_MONTH));
		uri.append("&c=").append(calendar.get(Calendar.YEAR));
		
		calendar.setTime(range.getEnd());
		uri.append("&d=").append(calendar.get(Calendar.MONTH));
		uri.append("&e=").append(calendar.get(Calendar.DAY_OF_MONTH));
		uri.append("&f=").append(calendar.get(Calendar.YEAR));
		uri.append("&g=d");
		uri.toString();
		
		return new URL(uri.toString());
	}
	
	private String[] readFromUrl(URL url) throws Exception {
	    URLConnection connection = url.openConnection();
	    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	    String inputLine;

	    ArrayList<String> content = new ArrayList<String>();
	    while ((inputLine = in.readLine()) != null) {
	        content.add(inputLine);
	    }
	    in.close();
	    
	    if (content.size() > 1)
	    	content.remove(0);
	    
	    Collections.reverse(content);
	    return content.toArray(new String[content.size()]);
	}
}
